import type { LocationQuery } from "vue-router";

/**
 * 用来解析http://localhost:5173/login?redirect=/documentation/index&a=1&b=2 回跳地址和参数
 */
function useQuery() {
  const redirect = ref("");
  const otherQuery = ref<LocationQuery>();
  const route = useRoute(); //获取当前路由 http://localhost:5173/login?redirect=/documentation/index&a=1&b=2

  console.log("route=====", route);

  const getOtherQuery = (query: LocationQuery) => {
    return Object.keys(query).reduce((memo, key) => {
      if (key !== "redirect") {
        memo[key] = query[key];
      }
      return memo;
    }, {} as LocationQuery);
  };

  //用watchEffect来监听路由变化
  watchEffect(() => {
    const query = route.query; // route.query = {a:1,b:2,redirect:"/documentation/index"}
    const otherParams = getOtherQuery(query);
    if (query) {
      redirect.value = query.redirect as string;
      otherQuery.value = otherParams;
    }
  });

  return {
    redirect, //redirect.value = "/documentation/index"
    otherQuery //otherQuery.value = {a:1,b:2}
  };
}

export { useQuery };
